<template>
  <div class="page login p10">
    <div class="form">
      <div class="form-area">
        <nut-textinput
          v-model="pageAjax.data.username"
          label="账号: "
          placeholder="请输入登陆账号"
        />
      </div>
      <div class="form-area">
        <nut-textinput
          v-model="pageAjax.data.password"
          label="密码: "
          type="password"
          placeholder="请输入登陆密码"
          :clearBtn="true"
          :disabled="false"
        />
      </div>
      <div class="form-area">
        <nut-button block type="default" @click="rSubmitForm">
          登录
        </nut-button>
      </div>
    </div>
  </div>
</template>
<script>
import { login } from "@/api/passport.js";
import { getUserInfo } from "@/api/user.js";

export default {
  name: "Home",
  data() {
    return {
      pageAjax: {
        loading: false,
        data: {
          username: "",
          password: "",
          user_type: 2,
          grant_type: "password"
        }
      },
      userData: {}
    };
  },
  methods: {
    rSubmitForm() {
      let _that = this;

      if (!_that.pageAjax.data.username) {
        _that.$toast.text("账号不能为空");
        return;
      }
      if (!_that.pageAjax.data.password) {
        _that.$toast.text("密码不能为空");
        return;
      }
      login(_that.pageAjax.data)
        .then(resp => {
          let respData = resp.data || {};
          if (respData.code === _that.STATUS.success[0]) {
            let sid = {
              access_token: respData.data.access_token
            };

            // localStorage.setItem("sid", JSON.stringify(sid));
            sessionStorage.setItem("sid", JSON.stringify(sid));

            _that.$store.commit("setSid", sid);

            _that.getUserInfo().then(() => {
              // localStorage.setItem("userData", JSON.stringify(_that.userData));
              sessionStorage.setItem(
                "userData",
                JSON.stringify(_that.userData)
              );
              _that.$store.commit("setUserData", _that.userData);

              _that.$router.push({ name: "info" });
              // _that.getUserInfo();
            });
          } else {
            _that.$toast.fail(respData.msg || "登陆出现错误");
          }
        })
        .finally(() => {
          _that.pageAjax.loading = false;
        });
    },
    getUserInfo() {
      let _that = this;

      return getUserInfo().then(userResp => {
        let userRespData = userResp.data || {};
        if (userRespData.code === _that.STATUS.success[0]) {
          _that.userData = userRespData.data;
        } else {
          _that.$message.error(userRespData.msg || "获取用户信息出现错误");
        }
      });
    }
  }
};
</script>
<style lang="scss">
.page {
  font-size: 20px;
  .form {
    margin-top: 100px;
    .form-area {
      margin-top: 10px;
    }
  }
}
</style>
